package com.example.authority.common.utils;

import com.example.authority.domain.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.List;
import java.util.Set;

public class SecurityUtils {
    public static LoginUser getCurrentUser() {
        Authentication loginUser =SecurityContextHolder.getContext().getAuthentication();
        if(loginUser == null) {
            return null;
        }
        return (LoginUser) loginUser.getPrincipal();
    }

    public static Set<GrantedAuthority> getAuthorities() {
        Authentication loginUser =SecurityContextHolder.getContext().getAuthentication();
        if(loginUser == null) {
            return null;
        }
        return (Set<GrantedAuthority>) loginUser.getAuthorities();
    }

    public static boolean hasRole(List<String> roles) {
        Set<GrantedAuthority> authorities = getAuthorities();
        if(authorities == null||authorities.isEmpty()) {
            return false;
        }
        for (String role : roles) {
            if (authorities.contains(new SimpleGrantedAuthority("ROLE_"+role))) {
                return true;
            }
        }
        return false;
    }

    public static boolean hasAuthority(List<String> authority) {
        Set<GrantedAuthority> authorities = getAuthorities();
        if(authorities == null||authorities.isEmpty()) {
            return false;
        }
        boolean flag = true;
        for (String s:
             authority) {
            if (!authorities.contains(new SimpleGrantedAuthority(s))) {
                flag = false;
                break;
            }
        }
        return flag;
    }
}
